import requests
from lxml import etree
import csv

url = 'http://www.piaofang.biz/'

res = requests.get(url)
res.encoding = 'gb2312'
html = res.text
tree = etree.HTML(html)
table = tree.xpath("//tr")
lst=[]

for tr in table:
    paiming = tr.xpath('./td[@class="num"]/text()')
    if paiming:
        paiming = paiming[0]
    else:
        continue

    try:
        movie = tr.xpath('./td[@class="title"]/a/text()')[0]
    except IndexError:
        movie = tr.xpath('./td[@class="title"]/text()')[0]
    publish = tr.xpath('./td[@class="year"]/text()')[0]
    form = tr.xpath('./td[@class="type"]/text()')[0]
    director = tr.xpath('./td[@class="daoyan"]/text()')[0]
    piaofang = tr.xpath('./td[@class="piaofang"]/span/text()')[0]
    tup = (paiming, movie, publish, form, director, piaofang)
    lst.append(tup)

head = ('排名', '电影名', '上映', '类型', '导演', '全球票房')

with open('movie.csv','w',encoding='utf-8-sig',newline='') as f:
    w = csv.writer(f)
    w.writerow(head)
    w.writerows(lst)

